package com.wecan.es.data.service;

import com.wecan.es.data.entity.Course;
import com.wecan.es.data.repository.CourseRepository;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CourserService {
    @Autowired
    private CourseRepository courseRepository;

    public Course insertCourse(Course course) {
        return courseRepository.save(course);
    }

    public List<Course> search(String param) {
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(param);
        Iterable<Course> search = courseRepository.search(builder);
        List<Course> courses = new ArrayList<>();
        if (search != null)
            search.forEach(courses::add);
        return courses;
    }

    public List<Course> searchPage(Integer page, Integer size, String param) {
        //分页参数
        Pageable pageable = PageRequest.of(page, size);
        //建立查询
        QueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("courseTitle", param))
                .should(QueryBuilders.matchQuery("courseIntroduce", param))
                .should(QueryBuilders.matchQuery("courseTeacher", param));
        //分页
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withPageable(pageable)
                .withQuery(queryBuilder)
                .build();
        //查询
        Page<Course> search = courseRepository.search(nativeSearchQuery);
        return search.getContent();

    }

    public void deleteCourse(String id) {
        courseRepository.deleteById(id);
    }

    public Course updateCourse(Course course) {
        return courseRepository.save(course);
    }
}
